package top.jacktgq.hsp.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @Author CandyWall
 * @Date 2020/11/13--0:11
 * @Description 使用Netty实现WebSocket服务器端
 */
public class WebSocketServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //因为是基于Http协议，所以需要使用Http的编解码器
                        pipeline.addLast(new HttpServerCodec());

                        //是以块方式写的，添加ChunkedWriteHandler
                        pipeline.addLast(new ChunkedWriteHandler());

                        /*
                            说明：
                            1、http数据在传输过程中是分段的，HTTPObjectAggregator，就是可以将多个段聚合起来
                            2、这就是为什么，当浏览器发送大量数据时，就会发出多次Http请求
                         */
                        pipeline.addLast(new HttpObjectAggregator(8192));

                        /*
                            说明：
                            1、对应WebSocket，它的数据是以帧（frame）形式进行传递的
                            2、可以看到WebSocketFrame下面有6个子类
                            3、浏览器发送请求时，ws://localhost:7000/xxx 表示请求的uri
                            4、WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议，保持长连接
                            5、是通过一个状态码 101将协议进行升级
                         */
                        pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                        //自定义Handler，处理业务逻辑
                        pipeline.addLast(new top.jacktgq.hsp.netty.websocket.MyTextWebSocketFrameHandler());
                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
